package com.sghd.fight.module.game.service.skill.alter;


import com.sghd.fight.module.game.core.model.Unit;

import java.util.*;
import java.util.Map.Entry;

/**
 * 战斗单元的数值变更对象
 */
@SuppressWarnings({ "rawtypes", "unchecked" })
public class AlterValue implements Cloneable{

	private final Map<AlterType, Object> content = new HashMap<>();

	public AlterValue clone() {
		AlterValue result = new AlterValue();
		result.content.putAll(this.content);
		return result;
	}

	/** 获取指定值 */
	public <T> T getValue(AlterType type, Class<T> clz) {
		return (T) content.get(type);
	}

	/** 添加值 */
	public void addValue(AlterType type, Object value) {
		Alter alter = type.getAlter();
		value = alter.add(content.get(type), (Number) value);
		content.put(type, value);
	}

	/** 检查是否存在指定的数值变更 */
	public boolean contain(AlterType type) {
		return content.containsKey(type);
	}

	/** 合并数值变更 */
	public void merge(AlterValue value) {
		for (Entry<AlterType, Object> entry : value.content.entrySet()) {
			AlterType type = entry.getKey();
			Alter alter = type.getAlter();
			Object current = content.get(type);
			current = alter.merge(current, entry.getValue());
			content.put(type, current);
		}
	}

	/** 将数值变更作用到战斗单元 */
	public void effect(Unit unit) {
		List<AlterType> types = new ArrayList<>();
		for (AlterType key : content.keySet()) {
			types.add(key);
		}
		Collections.sort(types);
		for (AlterType type : types) {
			Object value = content.get(type);
			Alter alter = type.getAlter();
			alter.execute(unit, value);
		}
	}

	// Getter and Setter ...

	public Map<AlterType, Object> getContent() {
		return content;
	}

	@Override
	public String toString() {
		return content.toString();
	}

	public void update(AlterType alterType, int value) {
		if(content.containsKey(alterType)){
			content.put(alterType, value);
		}
	}
}
